package com.wang.dao;

import com.wang.pojo.User;

import java.util.List;

public class UserDao extends BaseDao {

    public User queryUserByUsername(String username) {
        String sql = "select * from user where username = ?";
        return queryForOne(User.class, sql, username);
    }

    public User queryUserByName(String name) {
        String sql = "select * from user where name = ?";
        return queryForOne(User.class, sql, name);
    }

    public User queryUserByUsernameAndPassword(String username, String password) {
        String sql = "select * from user where username = ? and password = ?";
        return queryForOne(User.class, sql, username, password);
    }

    public User getUserById(int id) {
        String sql = "select * from user where id=?";
        return queryForOne(User.class, sql, id);
    }

    public int saveUser(User user) {
        System.out.println(user);
        String sql = "insert into user(username,name,password,email,privilege,face_path)" +
                " values(?,?,?,?,?,?)";
        return update(sql, user.getUserName(), user.getName(),
                user.getPassword(), user.getEmail(), user.getPrivilege(), user.getFace_path());
    }

    public int updateUserFace(int id, String face_path) {
        String sql = "update user set face_path = ? where id = ?";
        return update(sql, face_path, id);
    }

    public int updateUser(User newUser) {
        String sql = "update user set username = ?,name = ?,email = ?,privilege = ?,password = ? where id = ?";
        return update(sql, newUser.getUserName(), newUser.getName(), newUser.getEmail(),
                newUser.getPrivilege(), newUser.getPassword(),newUser.getId());
    }

    public int queryForPageTotalCount(User user) {
        String sql = "select count(*) from user where privilege>?";
        Number count = (Number) queryForValue(sql, user.getPrivilege());
        return count.intValue();
    }

    public List<User> queryForPageItems(int begin, int pageSize, User user) {
        String sql = "select * from user where privilege>? limit ?,?";
        return queryForList(User.class, sql, user.getPrivilege(), begin, pageSize);
    }

    public void deleteUserById(int id) {
        //暂时关闭外键检查
        closeForeignKeyCheck();
        String sql = "delete user,home from user,home where user.id=home.user_id and user.id = ?";
        update(sql, id);
        //防止由于用户没消费记录而删不掉
        sql = "delete from user where id = ?";
        update(sql, id);
        openForeignKeyCheck();
    }
}
